﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using TekaMUD.Engine.Blocks;
using System.Data.SqlServerCe;
using System.Data;
using TekaMUD.Engine.Framework;
using System.Diagnostics;

namespace TekaMUD.Engine.Persistence
{
	public class Storage
	{
		public static void LoadWorld()
		{
			try
			{
				SqlCeConnection conn = OpenConnection();
				
				LoadOptions(conn);

				LandStorage.LoadContinents(conn);
				
				conn.Close();

//				World.LoadWorld(w);
			}
			catch (Exception ex)
			{
				Logger.LogError("Error loading world: " + ex.Message);
				throw ex;
			}
		}

		private static void LoadOptions(SqlCeConnection conn)
		{
			SqlCeCommand cmd = new SqlCeCommand("select * from RuntimeOptions", conn);

			using (IDataReader r = cmd.ExecuteReader())
			{
				while (r.Read())
				{
					try
					{
						Logger.LogDebug("Setting option " + r["key"] + " = " + r["value"]);
						RuntimeOptions.SetOption(r["key"] as string, r["value"] as string);
					}
					catch (Exception ex)
					{
						Logger.LogError("Failed set option: " + ex.Message);
					}
				}
			}
		}

		/// <summary>
		/// Updates the world database to disk.
		/// </summary>
		public static void UpdateWorld()
		{
			SqlCeConnection conn = OpenConnection();
			UpdateRuntimeOptions(conn);

			conn.Close();
		}

		private static void UpdateRuntimeOptions(SqlCeConnection conn)
		{
			SqlCeCommand cmd = new SqlCeCommand("delete from runtimeoptions", conn);
			cmd.ExecuteNonQuery();


			foreach (KeyValuePair<string, string> kvp in RuntimeOptions.DumpOptions())
			{
				cmd = new SqlCeCommand("INSERT into RuntimeOptions([Key], [Value]) values (?, ?)", conn);

				cmd.Parameters.Add("1", kvp.Key);
				cmd.Parameters.Add("2", kvp.Value);

				cmd.ExecuteNonQuery();
			}
		}

		private static string GetPlayerDir()
		{
			return ConfigurationManager.AppSettings["PLAYER_DIR"];
		}
		
		private static SqlCeConnection OpenConnection()
		{
			string dbFile = Configuration.DB_FILE;
			SqlCeConnection conn = new SqlCeConnection("Data Source = " +  dbFile + ";");
			conn.Open();

			return conn;
		}

		public static string FixStringSeparations(string input)
		{
			if (input == null)
				return null;

			return input.Replace("\\n", "\n").Replace("\\t", "\t").Replace("\\r", "");
		}

		public static void x()
		{
		}
	}
}
